import React, { useState, useEffect, useRef, useCallback } from 'react'
import { View, Text, Button } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { Order, OrderStatus } from '../../types'
import { orderUtils } from '../../utils/orderUtils'
import { CloudDataManager } from '../../utils/cloud'
import './index.scss'

interface OrderTrackerProps {
  orderId: string;
  onStatusChange?: (status: OrderStatus) => void;
}

const OrderTracker: React.FC<OrderTrackerProps> = ({ orderId, onStatusChange }) => {
  const [order, setOrder] = useState<Order | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const watcherRef = useRef<any>(null)
  
  // 稳定的状态变更回调
  const stableOnStatusChange = useCallback((status: OrderStatus) => {
    onStatusChange?.(status)
  }, [onStatusChange])
  
  useEffect(() => {
    if (!orderId) return
    
    let isActive = true
    
    // 初始加载订单
    const loadOrder = async () => {
      try {
        setLoading(true)
        setError(null)
        
        const orderData = await CloudDataManager.getData('orders', orderId) as Order
        if (isActive && orderData) {
          setOrder(orderData)
          stableOnStatusChange(orderData.status)
        }
      } catch (err) {
        if (isActive) {
          console.error('获取订单失败:', err)
          setError('获取订单信息失败')
        }
      } finally {
        if (isActive) {
          setLoading(false)
        }
      }
    }
    
    loadOrder()
    
    // 设置实时监听（添加错误处理和重连机制）
    const setupWatcher = () => {
      try {
        watcherRef.current = CloudDataManager.watchCollection('orders', {
          onChange: (snapshot) => {
            if (!isActive) return
            
            const changedDocs = snapshot.docs || []
            const updatedOrder = changedDocs.find(doc => doc._id === orderId)
            
            if (updatedOrder) {
              setOrder(updatedOrder as unknown as Order)
              stableOnStatusChange(updatedOrder.status as OrderStatus)
            }
          },
          onError: (err) => {
            console.error('监听订单变化失败:', err)
            
            // 如果组件仍然活跃，尝试重新建立监听
            if (isActive) {
              setTimeout(() => {
                if (isActive) {
                  console.log('尝试重新建立订单监听')
                  setupWatcher()
                }
              }, 5000)
            }
          }
        }, { _id: orderId })
      } catch (error) {
        console.error('建立订单监听失败:', error)
      }
    }
    
    setupWatcher()
    
    // 清理函数
    return () => {
      isActive = false
      if (watcherRef.current) {
        try {
          watcherRef.current()
        } catch (error) {
          console.error('清理订单监听失败:', error)
        }
        watcherRef.current = null
      }
    }
  }, [orderId, stableOnStatusChange])
  
  const fetchOrder = async () => {
    if (!orderId) return
    
    setLoading(true)
    setError(null)
    
    try {
      const orderData = await CloudDataManager.getData('orders', orderId) as Order
      if (orderData) {
        setOrder(orderData)
        
        if (onStatusChange) {
          onStatusChange(orderData.status)
        }
      } else {
        setError('订单不存在')
      }
    } catch (err) {
      console.error('获取订单失败:', err)
      setError('获取订单信息失败')
    } finally {
      setLoading(false)
    }
  }
  
  // 计算预计送达时间
  const calculateEstimatedDeliveryTime = (): string => {
    if (!order || !order.createdAt || !order.estimatedTime) {
      return '未知'
    }
    
    const createdAt = new Date(order.createdAt)
    const estimatedDeliveryTime = new Date(createdAt.getTime() + order.estimatedTime * 60000)
    
    return `${estimatedDeliveryTime.getHours()}:${String(estimatedDeliveryTime.getMinutes()).padStart(2, '0')}`
  }
  
  // 获取当前状态索引
  const getCurrentStatusIndex = (): number => {
    if (!order) return 0
    
    const statusOrder: OrderStatus[] = ['pending', 'confirmed', 'completed', 'cancelled']
    return statusOrder.indexOf(order.status)
  }
  
  // 判断状态是否已完成
  const isStatusCompleted = (statusIndex: number): boolean => {
    const currentIndex = getCurrentStatusIndex()
    
    // 如果订单已取消，只有"已取消"状态为完成
    if (order?.status === 'cancelled') {
      return statusIndex === 3
    }
    
    return statusIndex <= currentIndex
  }
  
  if (loading) {
    return (
      <View className='order-tracker-loading'>
        <Text>加载订单信息...</Text>
      </View>
    )
  }
  
  if (error || !order) {
    return (
      <View className='order-tracker-error'>
        <Text>{error || '订单信息不可用'}</Text>
      </View>
    )
  }
  
  return (
    <View className='order-tracker'>
      {/* 订单基本信息 */}
      <View className='order-info'>
        <Text className='order-id'>订单号: {order.id}</Text>
        <Text className={`order-status ${order.status}`}>
          {orderUtils.formatOrderStatus(order.status)}
        </Text>
      </View>
      
      {/* 订单跟踪时间线 */}
      <View className='order-timeline'>
        {/* 待确认 */}
        <View className={`timeline-item ${isStatusCompleted(0) ? 'completed' : ''}`}>
          <View className='timeline-icon'>
            <Text className='icon'>📝</Text>
          </View>
          <View className='timeline-content'>
            <Text className='title'>订单已提交</Text>
            <Text className='time'>
              {new Date(order.createdAt).toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'})}
            </Text>
          </View>
        </View>
        
        {/* 已确认 */}
        <View className={`timeline-item ${isStatusCompleted(1) ? 'completed' : ''}`}>
          <View className='timeline-icon'>
            <Text className='icon'>👨‍🍳</Text>
          </View>
          <View className='timeline-content'>
            <Text className='title'>厨师已接单</Text>
            {order.assignedChefName && (
              <Text className='chef-name'>处理厨师: {order.assignedChefName}</Text>
            )}
            {order.status === 'confirmed' && order.estimatedTime && (
              <Text className='estimated-time'>预计完成时间: {calculateEstimatedDeliveryTime()}</Text>
            )}
          </View>
        </View>
        
        {/* 已完成或已取消 */}
        {order.status !== 'cancelled' ? (
          <View className={`timeline-item ${isStatusCompleted(2) ? 'completed' : ''}`}>
            <View className='timeline-icon'>
              <Text className='icon'>✅</Text>
            </View>
            <View className='timeline-content'>
              <Text className='title'>订单已完成</Text>
              {order.status === 'completed' && order.pointsEarned && (
                <Text className='points-earned'>获得积分: +{order.pointsEarned}</Text>
              )}
            </View>
          </View>
        ) : (
          <View className={`timeline-item ${isStatusCompleted(3) ? 'completed cancelled' : ''}`}>
            <View className='timeline-icon'>
              <Text className='icon'>❌</Text>
            </View>
            <View className='timeline-content'>
              <Text className='title'>订单已取消</Text>
              <Text className='cancel-time'>
                {new Date(order.updatedAt).toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'})}
              </Text>
            </View>
          </View>
        )}
      </View>
      
      {/* 订单进度提示 */}
      {order.status === 'confirmed' && (
        <View className='order-progress'>
          <Text className='progress-text'>
            厨师正在准备您的美食，请耐心等待...
          </Text>
        </View>
      )}
    </View>
  )
}

export default OrderTracker 